package com.hspedu.com.jdbc.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @author DL5O
 * @version 1.0
 */
public class JDBCUtils_Exercise {
    private static String user;
    private static String password;
    private static String url;
    private static String driver;

    //在静态代码块中去获取这些信息，即每次到这个工具类加载后都会有user，password等信息
    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src\\jdbc.properties"));
            user = properties.getProperty(user);
            password = properties.getProperty(password);
            url = properties.getProperty(url);
            driver = properties.getProperty(driver);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //写一个方法：用于进行数据库的连接，并返回connection
    public static Connection getConnection(){
        try {
            Class.forName(driver);
            return DriverManager.getConnection(url,user,password);
        } catch (SQLException | ClassNotFoundException throwables) {
            throw new RuntimeException(throwables);
        }
    }

    //写一个方法：关闭相关资源
    public static void close(ResultSet set, Statement statement,Connection connection){
        try {
            if (set != null) {
                set.close();
            }

            if (statement != null) {
                statement.close();
            }

            if (connection != null) {
                connection.close();
            }
        }catch (SQLException throwables){
            //将编译异常转成运行异常抛出
            throw new RuntimeException(throwables);
        }
    }
}
